package com.module.imagelib.glide;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.module.imagelib.R;
import com.module.imagelib.glide.progress.OnProgressListener;
import com.module.imagelib.glide.progress.ProgressManager;
import com.module.imagelib.glide.utils.ImageFileUtils;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 1.0版
 */
public class ImageLoader_v1 {

    private static ImageLoader_v1 instance;
    private final static Object syncLock = new Object();
    private static GlideHelper mGlideHelper;

    private ImageLoader_v1(){
        mGlideHelper = new GlideHelper();
    }

    public static ImageLoader_v1 getInstance() {
        if (instance == null) {
            synchronized (syncLock) {
                if (instance == null) {
                    instance = new ImageLoader_v1();
                }
            }
        }
        return instance;
    }

    /** ---普通版:普通默认图---*/
    public GlideHelper loadNormal(Context context, String url) {
        return load(context, url).cache().placeholder(R.mipmap.ic_launcher);
    }
    /** ---头像版:头像默认图---*/
    public GlideHelper loadHead(Context context, String url) {
        return load(context, url).cache().placeholder(R.mipmap.ic_launcher);
    }
    /** ---入口---*/
    public GlideHelper load(Context context, String url){
        mGlideHelper = mGlideHelper.load(context, url);
        return mGlideHelper;
    }



    public class GlideHelper{
        private RequestBuilder mGlideRequest;
        /** ---加载地址-Drawable---*/
        public GlideHelper load(Context context, String url) {
            mGlideRequest = Glide.with(context.getApplicationContext()).load(url);
            return this;
        }
        /** ---加载地址-Bitmap---*/
        public GlideHelper loadBitmap(Context context, String url) {
            mGlideRequest = Glide.with(context.getApplicationContext()).asBitmap().load(url);
            return this;
        }
        /** ---缓存模式---*/
        public GlideHelper cache() {
//            mGlideRequest.cache();
            return this;
        }
        /** ---默认图片---*/
        public GlideHelper placeholder(int resId) {
            mGlideRequest.placeholder(resId);
            return this;
        }
        /** ---图片尺寸---*/
        public GlideHelper size(int width, int height) {
            mGlideRequest.override(width, height);
            return this;
        }
        /** ---居中裁剪显示---*/
        public GlideHelper centerCrop() {
            mGlideRequest.centerCrop();
            return this;
        }
        /** ---动画-淡入淡出---*/
        public GlideHelper crossFade() {
            mGlideRequest.transition(DrawableTransitionOptions.withCrossFade());
            return this;
        }
        /** ---缩略图（列表使用）---*/
        public GlideHelper thumbnail(float sizeMultiplier) {
            mGlideRequest.thumbnail(sizeMultiplier);
            return this;
        }
        /** ---圆形---*/
        public GlideHelper circle() {
//            mGlideRequest.circle();
            return this;
        }
        /** ---圆角---*/
        public GlideHelper round(int radius) {
//            mGlideRequest.round(radius);
            return this;
        }
        /** ---优先级---*/
        public GlideHelper priority(Priority priority) {
            mGlideRequest.priority(priority);
            return this;
        }
        /** ---加载进度---*/
        public GlideHelper progress(final OnProgressListener listener) {
            //注册监听
            ProgressManager.addProgressListener(listener);
            //设置进度监听
            mGlideRequest = mGlideRequest.listener(new RequestListener() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                    //删除监听
                    ProgressManager.removeProgressListener(listener);
                    return false;
                }

                @Override
                public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                    //删除监听
                    ProgressManager.removeProgressListener(listener);
                    return false;
                }
            });
            return this;
        }
        /** ---暂停请求（列表使用）---*/
        public void pauseRequests(Context context) {
            Glide.with(context.getApplicationContext()).pauseRequests();
        }
        /** ---恢复请求（列表使用）---*/
        public void resumeRequests(Context context) {
            Glide.with(context.getApplicationContext()).resumeRequests();
        }
        /** ---清除内存缓存（主线程调用）---*/
        public void clearMemory(final Activity activity) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Glide.get(activity).clearMemory();
                }
            });
        }
        /** ---清除硬盘缓存（子线程中调用）---*/
        public void clearDiskCache(final Activity activity) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Glide.get(activity).clearDiskCache();
                }
            }).start();
        }
        /** ---输出控件---*/
        public void into(ImageView imageView) {
            mGlideRequest.into(imageView);
        }
        /** ---输出target---*/
        public void into(SimpleTarget<Bitmap> target) {
            mGlideRequest.into(target);
        }
        /** ---广告控件---*/
        /**
         * 按比例计算屏幕宽度对应的高度
         * 例：图片比例4:3 屏幕宽度1080 计算高度->810
         */
        public void into(ImageView imageView, int widthRatio, int heightRatio) {
            imageView.getLayoutParams().width = getScreenWidth();
            imageView.getLayoutParams().height = imageView.getLayoutParams().width * heightRatio / widthRatio;
            mGlideRequest.into(imageView);
        }


        /** ---下载原文件---*/
        public void download(Context context, String url) {
            Glide.with(context.getApplicationContext()).download(url).into(new SimpleTarget<File>() {
                @Override
                public void onResourceReady(@NonNull final File resource, @Nullable Transition<? super File> transition) {
                    // /data/user/0/com.dengqi.mymodule/cache/image_manager_disk_cache/b4c6b32304cb156e554f6c541520173d8870e7f1e8c97017f0a68f87da80106b.0
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            ImageFileUtils.copyFile(resource);
                        }
                    }).start();
                }
            });
        }


        // 屏幕宽度（像素）
        public int getScreenWidth() {
            return Resources.getSystem().getDisplayMetrics().widthPixels;
        }

    }
}

